package com.member.web.controller.activity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.member.common.utils.DateUtils;
import com.member.common.utils.ExcelHandle;
import com.member.entity.CarActivity;
import com.member.entity.ChuTuan;
import com.member.entity.EatActivity;
import com.member.entity.GoodsActivity;
import com.member.entity.Shopping;
import com.member.entity.StayActivity;
import com.member.entity.YeWu;
import com.member.entity.base.BaseModel;
import com.member.entity.dto.ChuTuanDTO;
import com.member.entity.dto.YeWuDTO;
import com.member.entity.vo.ChuTuanVo;
import com.member.entity.vo.YeWuVo;
import com.member.service.ActivityService;
import com.member.service.UserService;
import com.member.web.controller.BaseController;

@Controller
@RequestMapping("/activity")
public class ActivityController extends BaseController {
	@Autowired
	UserService userService;
	@Autowired
	ActivityService activityService;

	// 跳转添加活动信息概述页面
	@RequestMapping("/allActivityView")
	public String allActivityView() {
		return "activity/allActivity";
	}

	// 跳转添加活动信息概述页面
	@RequestMapping("/totalActivityView")
	public String totalActivityView() {
		return "activity/totalActivity";
	}

	// 跳转添加活动信息概述页面
	@RequestMapping("/businessActivityView")
	public String businessActivityView() {
		return "activity/businessActivityView";
	}

	// 跳转添加活动信息概述页面
	@RequestMapping("/unBusinessActivityView")
	public String unBusinessActivityView() {
		return "activity/unBusinessActivityView";
	}

	/**
	 * 添加出团活动
	 * 
	 * @param voActivity
	 * @return
	 */
	@RequestMapping("/InsertChuTuan")
	public String InsertChuTuan(ChuTuanDTO voActivity, Model model) {
		System.out.println(voActivity.toString());
		BaseModel result = activityService.insertChuTuanActivity(voActivity);
		if (!result.Successful) {
			model.addAttribute("ERROR", result.Message);
			model.addAttribute("voActivity", voActivity);
			return "activity/allActivity";
		} else {
			return "redirect:allActivityList";
		}
	}

	/**
	 * 添加业务活动界面
	 * 
	 * @return
	 */
	@RequestMapping("/yewuActivityView")
	public String yewuActivityView() {
		return "activity/yewuActivityView";
	}
	/**
	 * 礼品 修改页面
	 * 
	 * @return
	 */
	@RequestMapping("/lipinView")
	public String lipinView(String id,Model model) {
		 List<GoodsActivity> goods=	activityService.findLipinById(id);
		model.addAttribute("Data", goods);
		model.addAttribute("ActivityId", id);
		return "activity/lipinView";
	}
	/**
	 * 添加礼品
	 * 
	 * @return
	 */
	@RequestMapping("/insertLiPin")
	public String insertLiPin(GoodsActivity goodsActivtity,Model model) {
		activityService.insertLiPin(goodsActivtity);
		List<GoodsActivity> goods=	activityService.findLipinById(goodsActivtity.getActivityId());
		model.addAttribute("Data", goods);
		model.addAttribute("ActivityId", goodsActivtity.getActivityId());
		return "activity/lipinView";
	}
	/**
	 * 删除礼品
	 * 
	 * @return
	 */
	@RequestMapping("/deteleLiPin")
	public String deteleLiPin(String id,String activityId,Model model) {
		activityService.delLiPin(id, activityId);
		List<GoodsActivity> goods=	activityService.findLipinById(activityId);
		model.addAttribute("Data", goods);
		model.addAttribute("ActivityId",activityId);
		return "activity/lipinView";
	}

	/**
	 * 添加业务活动
	 * 
	 * @param shop
	 * @return
	 */
	@RequestMapping("/InsertYeWu")
	public String InsertYeWu(YeWuDTO shop) {
		activityService.insertYeWu(shop);
		return "redirect:yeWuActivityList";
	}
	@RequestMapping("/UpdateYeWu")
	public String updateYeWu(YeWuDTO shop) {
		System.out.println(shop.toString());
		activityService.updateYeWu(shop);
		return "redirect:yeWuActivityList";
	}

	/**
	 * 查询出团活动
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/allActivityList")
	public String allActivityList(Model model, Integer pageNum, Integer pageSize) {
		PageInfo<ChuTuan> list = activityService.allActivityList(pageNum, pageSize);
		model.addAttribute("page", list);
		return "activity/allActivityList";
	}
	/**
	 * 业务活动列表
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/yeWuActivityList")
	public String yeWuActivityList(Model model, Integer pageNum, Integer pageSize) {
		PageInfo<YeWu> list = activityService.yeWuActivityList(pageNum, pageSize);
		model.addAttribute("page", list);
		return "activity/yewuActivityList";
	}
	
	/**
	 * 查询出团活动详情
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/findChuTuanById")
	public String findChuTuanById(Model model, String id) {
		ChuTuanVo data= activityService.findChuTuanById(id);
		System.out.println(data.toString());
		model.addAttribute("Data", data);
		return "activity/activityDetail";
	}
	/**
	 * 查询活动套餐
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/findChuTuanTaoChanById")
	public String findChuTuanTaoChanById(Model model, String id) {
		System.out.println(activityService.findChuTuanTaoChanById(id).toString());
		model.addAttribute("Data", activityService.findChuTuanTaoChanById(id));
		return "activity/yewuActivityView";
	}
	/**
	 * 查询业务
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/findYeWuById")
	public String findYeWuById(Model model, String id) {
		YeWuVo vo=activityService.findYeWuVoById(id);
		model.addAttribute("Data", vo);
		model.addAttribute("TaoCan", activityService.findChuTuanTaoChanById(vo.getYewu().getActivityId()));
		System.out.println(vo.toString());
		return "activity/yewuActivityUpdateView";
	}
	
	@ResponseBody
	@RequestMapping("/findShoppingListByYeWuId")
	public List<Shopping> findShoppingListByYeWuId(Model model, String id) {
		 List<Shopping>  list=activityService.findShoppingListByYeWuId(id);
		return list;
	}
	
	
		// 导出转账表格 根据时间导出转账记录
		
		@RequestMapping(value="/chuTuanRecordExport", method = RequestMethod.POST)
		public void findAllTransferRecordByType(String id, HttpServletRequest request,
				HttpServletResponse response, HttpSession session) throws IOException {
			ExcelHandle handle = new ExcelHandle();
			String tempFilePath = request.getRealPath("/resources/moban/dcmb.xlsx");
			

			List<YeWu> yewulist=activityService.findYeWuListByActivityId(id);
			List<String> yewuCell = new ArrayList<String>();
			yewuCell.add("yewuid");
			yewuCell.add("position");
			yewuCell.add("lecturer");
			yewuCell.add("workers");
			yewuCell.add("creatTime");
			List<Map<String, Object>> yewuDataList = new ArrayList<Map<String, Object>>();
			for(YeWu yewu: yewulist){
				
				Map<String, Object> yewuMap = new HashMap<String, Object>();
				yewuMap.put("yewuid",yewu.getId());
				yewuMap.put("position",yewu.getPosition());
				yewuMap.put("lecturer",yewu.getLecturer());
				yewuMap.put("workers",yewu.getWorkers());
				yewuMap.put("creatTime",DateUtils.formatDate(yewu.getCreateTime(),"yyyy-MM-dd"));
				yewuDataList.add(yewuMap);
			}
			handle.writeListData(tempFilePath, yewuCell, yewuDataList,6);
			ChuTuanVo data= activityService.findChuTuanById(id);
			
			List<String> dataCell = new ArrayList<String>();
			dataCell.add("id");
			dataCell.add("startTime");
			dataCell.add("endTime");
			dataCell.add("dayNum");
			dataCell.add("loadStart");
			dataCell.add("loadEnd");
			dataCell.add("peopleNum");
			dataCell.add("managerName");
			dataCell.add("groupMonkeyStandard");
			dataCell.add("remark");
			dataCell.add("groupMonkey");
			dataCell.add("eveningSiteCost");
			dataCell.add("eveningShowCost");
			dataCell.add("eveningShareCost");
			dataCell.add("eveningWorkersCost");
			dataCell.add("siteCost");
			dataCell.add("sharedCost");
			dataCell.add("siteWorkerCost");
			dataCell.add("siteAllCost");
			dataCell.add("insuranceStandard");
			dataCell.add("insuranceCost");
			dataCell.add("serviceCost");
			dataCell.add("deliveryCost");
			dataCell.add("carCost");
			dataCell.add("dinghuoNum");
			dataCell.add("yshouhuokuanNum");
			dataCell.add("wshouhuokuanNum");
			dataCell.add("tuihuokuanNum");
			dataCell.add("shoukuanNum");
			dataCell.add("sendNum");
			dataCell.add("remainingCost");
			dataCell.add("earning");
			dataCell.add("lecturerCost");
	
			ChuTuan tuan=data.getTuan();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", tuan.getId());
			map.put("startTime", DateUtils.formatDate(tuan.getStartTime(),"yyyy-MM-dd"));
			map.put("endTime",   DateUtils.formatDate(tuan.getEndTime(),"yyyy-MM-dd"));
			map.put("dayNum",tuan.getDayNum());
			map.put("loadStart",tuan.getLoadStart());
			map.put("loadEnd", tuan.getLoadEnd());
			map.put("peopleNum", tuan.getPeopleNum());
			map.put("managerName", tuan.getManagerName());
			map.put("groupMonkeyStandard", tuan.getGroupMonkeyStandard());
			map.put("remark", tuan.getRemark());
			map.put("groupMonkey", tuan.getGroupMonkey());
			map.put("eveningSiteCost", tuan.getEveningSiteCost());
			map.put("eveningShowCost", tuan.getEveningShowCost());
			map.put("eveningShareCost", tuan.getEveningShareCost());
			map.put("eveningWorkersCost", tuan.getEveningWorkersCost());
			map.put("siteCost", tuan.getSiteCost());
			map.put("sharedCost", tuan.getSharedCost());
			map.put("siteWorkerCost", tuan.getSiteWorkerCost());
			map.put("siteAllCost", tuan.getSiteAllCost());
			map.put("insuranceStandard", tuan.getInsuranceStandard());
			map.put("insuranceCost", tuan.getInsuranceCost());
			map.put("serviceCost", tuan.getServiceCost());
			map.put("deliveryCost", tuan.getDeliveryCost());
			map.put("carCost", tuan.getCarCost());
			map.put("dinghuoNum", tuan.getDinghuoNum());
			map.put("yshouhuokuanNum", tuan.getYshouhuokuanNum());
			map.put("wshouhuokuanNum", tuan.getWshouhuokuanNum());
			map.put("tuihuokuanNum", tuan.getTuihuokuanNum());
			map.put("shoukuanNum", tuan.getShoukuanNum());
			map.put("sendNum", tuan.getSendNum());
			map.put("remainingCost", tuan.getRemainingCost());
			map.put("earning",tuan.getEarning());
			map.put("lecturerCost",tuan.getLecturerCost());
			
			handle.writeData(tempFilePath, dataCell, map, 0);
			
			List<String> eatCell = new ArrayList<String>();
			eatCell.add("eatDayNum");
			eatCell.add("eatPosition");
			eatCell.add("eatStandard");
			eatCell.add("eatRemark");
			eatCell.add("eatCost");
			List<EatActivity> eatlist=data.getEatList();
			List<Map<String, Object>> eatDataList = new ArrayList<Map<String, Object>>();
			for(EatActivity eat: eatlist){

				Map<String, Object> eatMap = new HashMap<String, Object>();
				eatMap.put("eatDayNum",eat.getDayNum());
				eatMap.put("eatPosition",eat.getEatPosition());
				eatMap.put("eatStandard",eat.getEatStandard());
				eatMap.put("eatRemark",eat.getEatRemark());
				eatMap.put("eatCost",eat.getEatCost());
				eatDataList.add(eatMap);
			}
			handle.writeListData(tempFilePath, eatCell, eatDataList, 1);
			
			List<String> stayCell = new ArrayList<String>();
			stayCell.add("stayDayNum");
			stayCell.add("stayPosition");
			stayCell.add("stayStandard");
			stayCell.add("stayRemark");
			stayCell.add("stayCost");
			List<StayActivity> staylist=data.getStayList();
			List<Map<String, Object>> stayDataList = new ArrayList<Map<String, Object>>();
			for(StayActivity stay: staylist){
				Map<String, Object> stayMap = new HashMap<String, Object>();
				stayMap.put("stayDayNum",stay.getDayNum());
				stayMap.put("stayPosition",stay.getStayPosition());
				stayMap.put("stayStandard",stay.getStayStandard());
				stayMap.put("stayRemark",stay.getStayRemark());
				stayMap.put("stayCost",stay.getStayCost());
				stayDataList.add(stayMap);
			}
			handle.writeListData(tempFilePath, stayCell, stayDataList, 2);

			List<String> lipinCell = new ArrayList<String>();
			lipinCell.add("lipinName");
			lipinCell.add("lipinSpec");
			lipinCell.add("lipinPrice");
			lipinCell.add("lipinCount");
			lipinCell.add("lipinCost");
			List<GoodsActivity>lipinlist=data.getTaochanList();
			List<Map<String, Object>> lipinDataList = new ArrayList<Map<String, Object>>();
			for(GoodsActivity lipin: lipinlist){
				
				Map<String, Object> lipinMap = new HashMap<String, Object>();
				lipinMap.put("lipinName",lipin.getGoodsName());
				lipinMap.put("lipinSpec",lipin.getGoodsSpec());
				lipinMap.put("lipinPrice",lipin.getGoodsPrice());
				lipinMap.put("lipinCount",lipin.getGoodsCount());
				lipinMap.put("lipinCost",lipin.getGoodsCost());
				lipinDataList.add(lipinMap);
			}
			handle.writeListData(tempFilePath, lipinCell, lipinDataList, 3);
			
			List<String> taoCanCell = new ArrayList<String>();
			taoCanCell.add("taoCanName");
			taoCanCell.add("taoCanSpec");
			taoCanCell.add("taoCanPrice");
			taoCanCell.add("taoCanCount");
			taoCanCell.add("taoCanCost");
			List<GoodsActivity> taoCanlist=data.getTaochanList();
			List<Map<String, Object>> taoCanDataList = new ArrayList<Map<String, Object>>();
			for(GoodsActivity taocan: taoCanlist){
				
				Map<String, Object> taoCanMap = new HashMap<String, Object>();
				taoCanMap.put("taoCanName",taocan.getGoodsName());
				taoCanMap.put("taoCanSpec",taocan.getGoodsSpec());
				taoCanMap.put("taoCanPrice",taocan.getGoodsPrice());
				taoCanMap.put("taoCanCount",taocan.getGoodsCount());
				taoCanMap.put("taoCanCost",taocan.getGoodsCost());
				taoCanDataList.add(taoCanMap);
			}
			handle.writeListData(tempFilePath, taoCanCell, taoCanDataList, 4);

			
			
			List<String> carCell = new ArrayList<String>();
			carCell.add("carModel");
			carCell.add("carSite");
			carCell.add("carNum");
			carCell.add("carStandard");
			carCell.add("carCost");
			List<CarActivity> carlist=data.getCarList();
			List<Map<String, Object>> carDataList = new ArrayList<Map<String, Object>>();
			for(CarActivity car: carlist){
				
				Map<String, Object> carMap = new HashMap<String, Object>();
				carMap.put("carModel",car.getCarModel());
				carMap.put("carSite",car.getCarSite());
				carMap.put("carNum",car.getCarNum());
				carMap.put("carStandard",car.getCarStandard());
				carMap.put("carCost",car.getCarCost());
				carDataList.add(carMap);
			}
			handle.writeListData(tempFilePath, carCell, carDataList,5);
			
			
		
			List<String> shoppingCell = new ArrayList<String>();
			shoppingCell.add("userName");
			shoppingCell.add("userPhone");
			shoppingCell.add("bussinessName");
			shoppingCell.add("address");
			shoppingCell.add("deposit");
			shoppingCell.add("advance");
			shoppingCell.add("weikuan");
			shoppingCell.add("paid");
			shoppingCell.add("payType");
			shoppingCell.add("state");
		
			List<Map<String, Object>> shoppingDataList = new ArrayList<Map<String, Object>>();
			for(YeWu yewu: yewulist){
				List<Shopping>  shoppinglist=activityService.findShoppingListByYeWuId(yewu.getId());
				for(Shopping shopping: shoppinglist){
				
					Map<String, Object> shoppingMap = new HashMap<String, Object>();
					shoppingMap.put("userName",shopping.getUserName());
					shoppingMap.put("userPhone",shopping.getUserPhone());
					shoppingMap.put("bussinessName",shopping.getManagerName());
					shoppingMap.put("address",shopping.getAddress());
					shoppingMap.put("deposit",shopping.getDeposit());
					shoppingMap.put("advance",shopping.getAdvance());
					shoppingMap.put("weikuan",shopping.getWeikuan());
					shoppingMap.put("paid",shopping.getPaid());
					shoppingMap.put("payType",shopping.getPayType());
					if(1==shopping.getState()){
						shoppingMap.put("state","是");
					}else{
						shoppingMap.put("state","否");
					}
				
					shoppingDataList.add(shoppingMap);
				}
			}
			handle.writeListData(tempFilePath, shoppingCell, shoppingDataList,7);
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			// 写到输出流并关闭资源
			handle.writeAndClose(tempFilePath, os);
			byte[] content = os.toByteArray();
			os.flush();
			os.close();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面、
			String fileName = id + "-出团记录";
			
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
						
			String agent = request.getHeader("USER-AGENT").toLowerCase();
			String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			if (agent.contains("firefox")) {
				System.out.println("火狐浏览器");
				response.setCharacterEncoding("utf-8");
				response.setHeader("content-disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "ISO8859-1"));
			} else {
				response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xlsx");
			}

			ServletOutputStream out = response.getOutputStream();
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				bis = new BufferedInputStream(is);
				bos = new BufferedOutputStream(out);
				byte[] buff = new byte[2048];
				int bytesRead;
				// Simple read/write loop.
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				throw e;
			} finally {
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
				
			}

			handle.readClose(tempFilePath);
			

		}
		
		@RequestMapping("/deleteChuTuanById")
		public String deleteChuTuanById(Model model, String id) {
			activityService.deleteChuTuanById(id);
			return "redirect:allActivityList";
		}
}
